{% extends "admin/admin_base.html" %}

{% block title %}仪表盘 - 系统管理后台{% endblock %}
{% block breadcrumb %}仪表盘{% endblock %}
{% block content %}
<style>
    /* 统一左右卡片高度，flex 布局 */
    .charts-row .chart-card {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        min-height: 350px; /* 统一最小高度 */
    }

    /* 图表容器填满剩余空间 */
    .chart-wrapper {
        flex-grow: 1;
        padding: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    /* canvas 自适应父容器 */
    .chart-wrapper canvas {
        width: 100% !important;
        height: 100% !important;
    }

    /* 表头：标题 + 按钮对齐 */
    .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
    }

    /* 调整按钮样式 */
    .table-actions .btn {
        margin-left: 5px;
    }

/* 补充图表加载/空数据样式 */
/* 图表加载状态：居中显示 */
.chart-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 10;
}

/* 图表空数据状态：居中显示 */
.chart-empty {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #6B7785;
}

/* 时间范围按钮样式（与系统设置页面统一） */
.time-btn {
    border-radius: 4px;
    padding: 6px 16px;
    margin-left: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
}
.time-btn:hover {
    color: #165DFF;
    border-color: #165DFF;
}
.time-btn.active {
    background-color: #165DFF;
    color: #fff !important;
    border-color: #165DFF;
}

/* 响应式适配 */
@media (max-width: 992px) {
    .col-lg-8, .col-lg-4 {
        flex: 0 0 100%;
        max-width: 100%;
    }
    .chart-wrapper {
        height: 300px !important;
    }
}
</style>
<!--<h2 class="mb-4">仪表盘</h2>-->

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-6 col-lg-3 mb-3">
        <div class="stat-card">
            <div class="stat-card-header">
                <span class="stat-card-title">总用户数</span>
                <div class="stat-card-icon"
                     style="background-color: rgba(22, 93, 255, 0.15); color: var(--primary-color);">
                    <i class="fas fa-users"></i>
                </div>
            </div>
            <div class="stat-card-value">{{ stats.total_users }}</div>
            <div class="stat-card-trend trend-{{ 'up' if stats.total_users_growth  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if stats.total_users_growth  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if stats.total_users_growth  > 0 else '下降' }} {{ stats.total_users_growth }}% </span>
        </div>
        </div>
    </div>

    <div class="col-md-6 col-lg-3 mb-3">
        <div class="stat-card">
            <div class="stat-card-header">
                <span class="stat-card-title">今日新增用户</span>
                <div class="stat-card-icon"
                     style="background-color: rgba(0, 180, 42, 0.15); color: var(--success-color);">
                    <i class="fas fa-user-plus"></i>
                </div>
            </div>
            <div class="stat-card-value">{{ stats.today_new_users }}</div>
            <div class="stat-card-trend trend-{{ 'up' if stats.today_user_growth  > 0 else 'down' }}">
                <i class="fas fa-arrow-{{ 'up' if stats.today_user_growth  > 0 else 'down' }}"></i>
                <span>较昨日{{ '增长' if stats.today_user_growth  > 0 else '下降' }} {{ stats.today_user_growth }}% </span>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-lg-3 mb-3">
        <div class="stat-card">
            <div class="stat-card-header">
                <span class="stat-card-title">本月订单数</span>
                <div class="stat-card-icon"
                     style="background-color: rgba(255, 125, 0, 0.15); color: var(--warning-color);">
                    <i class="fas fa-shopping-cart"></i>
                </div>
            </div>
            <div class="stat-card-value">{{ stats.this_month_orders }}</div>
            <div class="stat-card-trend trend-{{ 'up' if stats.month_order_growth  > 0 else 'down' }}">
                <i class="fas fa-arrow-{{ 'up' if stats.month_order_growth  > 0 else 'down' }}"></i>
                <span> 较上月{{ '增长' if stats.month_order_growth  > 0 else '下降' }} {{ stats.month_order_growth }}%</span>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-lg-3 mb-3">
        <div class="stat-card">
            <div class="stat-card-header">
                <span class="stat-card-title">API调用次数</span>
                <div class="stat-card-icon"
                     style="background-color: rgba(245, 63, 63, 0.15); color: var(--danger-color);">
                    <i class="fas fa-exchange-alt"></i>
                </div>
            </div>
            <div class="stat-card-value">{{ stats.today_api_calls }}</div>
            <div class="stat-card-trend trend-{{ 'up' if stats.api_calls_growth > 0 else 'down' }}">
                <i class="fas fa-arrow-{{ 'up' if stats.api_calls_growth > 0 else 'down' }}"></i>
                <span>较昨日{{ '增长' if stats.api_calls_growth > 0 else '下降' }} {{ stats.api_calls_growth }}% </span>
            </div>
        </div>
    </div>

</div>

<!-- 图表 -->
<div class="row mb-4 charts-row">
    <!-- 左侧折线图：API调用趋势 -->
    <div class="col-lg-8 mb-4">
        <div class="data-table chart-card">
            <div class="table-header">
                <div class="table-title">API调用趋势</div>
                <div class="table-actions">
                    <button class="btn btn-outline time-btn active" data-range="week">本周</button>
                    <button class="btn btn-outline time-btn" data-range="month">本月</button>
                    <button class="btn btn-outline time-btn" data-range="year">全年</button>
                </div>
            </div>
            <!-- 图表容器：添加加载状态 -->
            <div class="chart-wrapper">
                <!-- 加载中提示 -->
                <div id="apiCallLoading" class="chart-loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <!-- 图表Canvas -->
                <canvas id="apiCallChart"></canvas>
                <!-- 空数据提示 -->
                <div id="apiCallEmpty" class="chart-empty d-none">
                    <i class="fas fa-chart-line text-muted" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">暂无API调用数据</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 右侧饼图：用户类型分布 -->
    <div class="col-lg-4 mb-4">
        <div class="data-table chart-card">
            <div class="table-header">
                <div class="table-title">用户类型分布</div>
            </div>
            <!-- 图表容器：添加加载状态 -->
            <div class="chart-wrapper d-flex justify-content-center align-items-center">
                <!-- 加载中提示 -->
                <div id="userTypeLoading" class="chart-loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <!-- 图表Canvas -->
                <canvas id="userTypeChart"></canvas>
                <!-- 空数据提示 -->
                <div id="userTypeEmpty" class="chart-empty d-none">
                    <i class="fas fa-users text-muted" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">暂无用户数据</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 最近订单 -->
<div class="data-table mb-4">
    <div class="table-header">
        <div class="table-title">最近订单</div>
        <div class="table-actions">
            <a href="/admin/orders" class="btn btn-outline">查看全部</a>
        </div>
    </div>
    <div class="table-responsive">
        <table>
            <thead>
            <tr>
                <th>订单ID</th>
                <th>用户</th>
                <th>卡密类型</th>
                <th>支付方式</th>
                <th>金额</th>
                <th>状态</th>
                <th>创建时间</th>
            </tr>
            </thead>
            <tbody>
            {% for order in recent_orders %}
            <tr>
                <td>{{ order.order_id }}</td>
                <td>{{ order.username }}</td>
                <td>
                    {% if order.vip_type == 'month' %}
                    <span class="badge badge-month">月卡</span>
                    {% elif order.vip_type == 'season' %}
                    <span class="badge badge-season">半年卡</span>
                    {% elif order.vip_type == 'year' %}
                    <span class="badge badge-year">年卡</span>
                    {% else %}
                    <span class="badge badge-free">其它</span>
                    {% endif %}
                </td>
                <td>
                {% if order.pay_type == 'wechat' %}
                        <span class="badge badge-free">
                            <img src="/static/images/wxpay.png" alt="微信" style="width: 20px; margin-right: 5px;">
                            微信
                        </span>
                    {% elif order.pay_type == 'alipay' %}
                        <span class="badge badge-free">
                            <img src="/static/images/alipay.png" alt="支付宝" style="width: 20px; margin-right: 5px;">
                            支付宝
                        </span>
                    {% elif order.pay_type == 'kami' %}
                        <span class="badge badge-free">
                            <img src="/static/images/kami.png" alt="卡密" style="width: 20px; margin-right: 5px;">
                            卡密
                        </span>
                    {% else %}
                    <span class="badge badge-free">other</span>
                    {% endif %}

                </td>
                <td>¥{{ order.amount }}</td>
                <td><span class="badge badge-{{ order.status_class }}">{{ order.status_label }}</span></td>
                <td>{{ order.created_at }}</td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
</div>

{% endblock %}
{% block scripts %}
<script src="/static/js/chart.js"></script>
<script>
// 全局图表实例（用于后续更新/销毁）
let apiCallChart = null;
let userTypeChart = null;

// 1. 加载API调用趋势数据（对接后端接口）
function loadApiTrend(range = "week") {
    // 显示加载状态，隐藏图表和空数据
    const loadingEl = document.getElementById("apiCallLoading");
    const chartEl = document.getElementById("apiCallChart");
    const emptyEl = document.getElementById("apiCallEmpty");
    loadingEl.classList.remove("d-none");
    chartEl.classList.add("d-none");
    emptyEl.classList.add("d-none");

    // 调用后端接口
    fetch(`/admin/api_trend?time_range=${range}`, {
        credentials: "include"  // 携带登录Cookie，确保权限验证通过
    })
    .then(response => {
        if (!response.ok) throw new Error(`HTTP错误：${response.status}`);
        return response.json();
    })
    .then(res => {
        if (res.success && res.data) {
            const { labels, values } = res.data;
            // 数据为空时显示空提示
            if (labels.length === 0 || values.every(v => v === 0)) {
                loadingEl.classList.add("d-none");
                emptyEl.classList.remove("d-none");
                return;
            }
            // 初始化/更新折线图
            initApiCallChart(labels, values);
            // 显示图表，隐藏加载
            loadingEl.classList.add("d-none");
            chartEl.classList.remove("d-none");
        } else {
            throw new Error(res.msg || "获取趋势数据失败");
        }
    })
    .catch(error => {
        console.error("加载API趋势数据失败：", error);
        // 显示空数据提示（或错误提示，根据需求调整）
        loadingEl.classList.add("d-none");
        emptyEl.classList.remove("d-none");
        emptyEl.querySelector("p").textContent = "加载失败，请刷新重试";
    });
}

// 2. 加载用户类型分布数据（对接后端接口）
function loadUserDistribution() {
    // 显示加载状态，隐藏图表和空数据
    const loadingEl = document.getElementById("userTypeLoading");
    const chartEl = document.getElementById("userTypeChart");
    const emptyEl = document.getElementById("userTypeEmpty");
    loadingEl.classList.remove("d-none");
    chartEl.classList.add("d-none");
    emptyEl.classList.add("d-none");

    // 调用后端接口
    fetch("/admin/user_distribution", {
        credentials: "include"
    })
    .then(response => {
        if (!response.ok) throw new Error(`HTTP错误：${response.status}`);
        return response.json();
    })
    .then(res => {
        if (res.success && res.data) {
            const { labels, values } = res.data;
            // 数据为空时显示空提示
            if (labels.length === 0 || values.every(v => v === 0)) {
                loadingEl.classList.add("d-none");
                emptyEl.classList.remove("d-none");
                return;
            }
            // 初始化/更新饼图
            initUserTypeChart(labels, values);
            // 显示图表，隐藏加载
            loadingEl.classList.add("d-none");
            chartEl.classList.remove("d-none");
        } else {
            throw new Error(res.msg || "获取用户分布数据失败");
        }
    })
    .catch(error => {
        console.error("加载用户分布数据失败：", error);
        // 显示空数据提示
        loadingEl.classList.add("d-none");
        emptyEl.classList.remove("d-none");
        emptyEl.querySelector("p").textContent = "加载失败，请刷新重试";
    });
}

// 3. 初始化/更新折线图（API调用趋势）
// 初始化/更新折线图（API调用趋势）
function initApiCallChart(labels, values) {
    const ctx = document.getElementById("apiCallChart").getContext("2d");
    if (apiCallChart) apiCallChart.destroy();

    apiCallChart = new Chart(ctx, {
        type: "line",
        data: {
            labels: labels,  // 后端返回的月份标签（如：01月, 02月）
            datasets: [{
                label: "API调用次数",
                data: values,
                backgroundColor: "rgba(22, 93, 255, 0.2)",
                borderColor: "rgba(22, 93, 255, 1)",
                borderWidth: 2,
                tension: 0.3,
                fill: true,
                pointBackgroundColor: "rgba(22, 93, 255, 1)",
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: "top",
                    labels: {
                        boxWidth: 12,
                        padding: 15,
                        font: { size: 12 }
                    }
                },
                tooltip: {
                    backgroundColor: "rgba(0, 0, 0, 0.7)",
                    padding: 10,
                    callbacks: {
                        label: function(ctx) {
                            return `调用次数：${ctx.raw} 次`;
                        },
                        title: function(ctx) {
                            return `月份：${ctx[0].label}`;  // 显示月份标题
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: {
                        font: { size: 11 },
                        maxRotation: 45,  // 旋转标签避免重叠
                        minRotation: 45,
                        padding: 10  // 增加标签间距
                    }
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        font: { size: 11 },
                        precision: 0
                    },
                    grid: {
                        color: "#f0f0f0"
                    }
                }
            }
        }
    });
}

// 4. 初始化/更新饼图（用户类型分布）
function initUserTypeChart(labels, values) {
    const ctx = document.getElementById("userTypeChart").getContext("2d");
    // 销毁已有图表实例
    if (userTypeChart) userTypeChart.destroy();

    // 饼图颜色（与用户类型对应，固定顺序）
    const colors = [
        "#8884d8",  // Free
        "#165DFF",  // Month（主色）
        "#FAAD14",  // Season（橙色）
        "#52C41A",  // Year（绿色）
        "#FF4D4F"   // Admin（红色）
    ];

    userTypeChart = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: labels,  // 后端返回的用户类型标签
            datasets: [{
                data: values,  // 后端返回的用户数量
                backgroundColor: colors,
                borderColor: "#fff",  // 白色边框，区分扇区
                borderWidth: 2,
                hoverOffset: 10  // 鼠标悬浮时扇区偏移，增强交互感
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: "bottom",
                    labels: {
                        boxWidth: 12,
                        padding: 15,
                        font: { size: 12 },
                        // 图例文本与数据对应（显示“类型：数量”）
                        generateLabels: function(chart) {
                            const datasets = chart.data.datasets;
                            return chart.data.labels.map((label, i) => {
                                const value = datasets[0].data[i];
                                return {
                                    text: `${label}：${value} 个`,
                                    fillStyle: datasets[0].backgroundColor[i],
                                    strokeStyle: datasets[0].borderColor[i],
                                    lineWidth: datasets[0].borderWidth,
                                    hidden: false
                                };
                            });
                        }
                    }
                },
                tooltip: {
                    backgroundColor: "rgba(0, 0, 0, 0.7)",
                    padding: 10,
                    titleFont: { size: 14 },
                    bodyFont: { size: 13 },
                    callbacks: {
                        label: function(ctx) {
                            const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = total > 0 ? ((ctx.raw / total) * 100).toFixed(1) : 0;
                            return `${ctx.label}：${ctx.raw} 个 (${percentage}%)`;
                        }
                    }
                }
            },
            cutout: "60%",  // 环形比例（60%空心）
            animation: {
                animateScale: true,  // 加载时缩放动画
                animateRotate: true  // 加载时旋转动画
            }
        }
    });
}

// 5. 绑定时间范围切换事件
function bindTimeRangeEvents() {
    const timeBtns = document.querySelectorAll(".time-btn");
    timeBtns.forEach(btn => {
        btn.addEventListener("click", function() {
            // 切换按钮激活状态
            timeBtns.forEach(b => b.classList.remove("active"));
            this.classList.add("active");
            // 获取选中的时间范围，加载对应数据
            const range = this.getAttribute("data-range");
            loadApiTrend(range);
        });
    });
}

// 6. 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function() {
    // 设置图表容器高度（关键：避免图表显示异常）
    const chartWrappers = document.querySelectorAll(".chart-wrapper");
    chartWrappers.forEach(wrapper => {
        wrapper.style.height = "350px";
        wrapper.style.position = "relative";  // 用于加载状态居中
    });

    // 初始化加载数据
    loadApiTrend();          // 默认加载“本周”趋势数据
    loadUserDistribution();  // 加载用户分布数据

    // 绑定时间范围切换事件
    bindTimeRangeEvents();
});
</script>

{% endblock %}
